<template>
  <div class="order-management">
    <PageLayout>


      <template #search>
        <n-collapse>
          <n-collapse-item name="1">
            <div class="compact-search-container">
              <n-form inline :model="searchForm" label-placement="left" class="compact-search-form">

                <n-form-item label="用户ID">
                  <n-input v-model:value="searchForm.id" placeholder="请输入用户ID" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="用户名">
                  <n-input v-model:value="searchForm.uname" placeholder="请输入用户名" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="密码">
                  <n-input v-model:value="searchForm.acrossNum" placeholder="请输入用户密码" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="加密后密码">
                  <n-input v-model:value="searchForm.encryptPwd" placeholder="请输入加密密码" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="加密算法">
                  <n-input v-model:value="searchForm.encryptionAlgorithm" placeholder="请输入加密算法" clearable
                    class="compact-input" size="large" />
                </n-form-item>

                <n-form-item label="邮箱">
                  <n-input v-model:value="searchForm.email" placeholder="请输入邮箱" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="电话号码">
                  <n-input v-model:value="searchForm.telNum" placeholder="请输入电话号码" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="微信">
                  <n-input v-model:value="searchForm.wechatAbt" placeholder="请输入微信号码" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="头像链接">
                  <n-input v-model:value="searchForm.avatarUrl" placeholder="请输入头像链接" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="角色编号">
                  <n-input v-model:value="searchForm.avatarUrl" placeholder="请输入角色编号douh" clearable
                    class="compact-input" size="large" />
                </n-form-item>

                <n-form-item label="是否冻结">
                  <n-select v-model:value="searchForm.freezeOrnnt" placeholder="请选择" :options="productFreezeOptions"
                    clearable class="compact-select" size="large" />
                </n-form-item>

                <n-form-item label="创建时间">
                  <n-input v-model:value="searchForm.createTm" placeholder="请选择创建时间" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="修改时间">
                  <n-input v-model:value="searchForm.updateTm" placeholder="请选择修改时间" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="账户金额">
                  <n-input-number v-model:value="searchForm.accountMoney" placeholder="请输入账户余额" clearable
                    class="compact-input" size="large" :precision="4" :min="0"
                    :formatter="(value) => `${value}`.replace(/[^\d.]/g, '')"
                    :parse="(value) => parseFloat(value) || 0" />
                </n-form-item>

                <n-form-item label="购买余额">
                  <n-input-number v-model:value="searchForm.bAccount" placeholder="请输入购买" clearable
                    class="compact-input" size="large" :precision="4" :min="0"
                    :formatter="(value) => `${value}`.replace(/[^\d.]/g, '')"
                    :parse="(value) => parseFloat(value) || 0" />
                </n-form-item>

                <n-form-item>
                  <n-space size="large">
                    <n-button type="primary" @click="handleSearch" size="large" class="compact-btn">
                      <template #icon>
                        <n-icon>
                          <SearchOutline />
                        </n-icon>
                      </template>
                      搜索
                    </n-button>
                    <n-button @click="handleReset" size="large" class="compact-btn">
                      <template #icon>
                        <n-icon>
                          <RefreshOutline />
                        </n-icon>
                      </template>
                      重置
                    </n-button>

                  </n-space>
                </n-form-item>
              </n-form>
            </div>
            <template #header>
              <n-text type="info">
                <span style="font-size: 15px;font-weight: 700;">搜索用户</span>
              </n-text>
            </template>
            <template #header-extra>
              <n-text type="info">
                <span style="color: coral;">邮件、电话号码、微信、头像链接支持模糊查询</span>
              </n-text>
            </template>
          </n-collapse-item>
        </n-collapse>
      </template>

      <!-- 表格头部 -->
      <template #header>
        <div class="compact-table-header">
          <!-- <n-button type="primary" @click="handleAdd" class="compact-add-btn" size="large">
            <template #icon>
              <n-icon>
                <AddOutline />
              </n-icon>
            </template>
新增用户
</n-button> -->
          <n-button type="info" @click="handleRefresh" class="compact-add-btn" size="large">
            <template #icon>
              <n-icon>
                <RefreshOutline />
              </n-icon>
            </template>
            刷新数据
          </n-button>
        </div>
      </template>

      <!-- 表格内容 -->
      <template #table>
        <n-data-table :columns="columns" :data="tableData" :loading="loading" :single-line="false" :scroll-x="3000"
          :flex-height="true" class="data-table" striped :row-key="(row) => row.orderId"
          :checked-row-keys="checkedRowKeys" @update:checked-row-keys="handleCheckedRowKeysChange"
          :row-class-name="getRowClassName" @row-click="handleRowClick" />
      </template>

      <!-- 分页 -->
      <template #pagination>
        <n-pagination v-model:page="pagination.page" v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount" :page-sizes="[10, 20, 50, 100, 200]" show-size-picker show-quick-jumper
          :prefix="paginationPrefix" @update:page="handlePageChange" @update:page-size="handlePageSizeChange" />
      </template>
    </PageLayout>














    <!-- 新增用户 -->
    <!-- <n-modal v-model:show="showOrderModal" :mask-closable="false" preset="card" :title="modalTitle" class="modern-modal"
      :style="{ width: '800px' }" :auto-focus="false" :close-on-esc="false" transform-origin="center">

      <template #header>
        <div class="modal-header">
          <div class="modal-title-wrapper">
            <n-icon size="24" class="modal-icon">
              <AddOutline v-if="modalMode === 'add'" />
              <CreateOutline v-else-if="modalMode === 'edit'" />
              <EyeOutline v-else />
            </n-icon>
            <div class="modal-title-text">
              <h3>{{ modalTitle }}</h3>
              <p class="modal-subtitle">{{ modalMode === 'add' ? '创建新的用户' : modalMode === 'edit' ? '修改用户信息' : '查看用户详情'
              }}</p>
            </div>
          </div>
        </div>
      </template>

      <template #default>
        <div class="modal-content">
          <n-form ref="addProductFormRef" :model="orderForm" :rules="productFormRules" label-placement="top"
            class="modern-form" :disabled="modalMode === 'view'">
            <div class="form-grid">
              <div class="form-section">
                <h4 class="section-title">基本信息</h4>
                <div class="form-row">
                  <n-form-item label="用户ID" path="id" class="form-item">
                    <n-input v-model:value="orderForm.id" class="modern-input" :disabled="true" />
                  </n-form-item>
                  <n-form-item label="用户名" path="productName" class="form-item">
                    <n-input v-model:value="orderForm.uname" placeholder="请输入用户名" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="商品描述" path="productDesc" class="form-item">
                    <n-input v-model:value="orderForm.productDesc" placeholder="请输入商品描述" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                  <n-form-item label="标签1" path="productTagDesc1" class="form-item">
                    <n-input v-model:value="orderForm.productTagDesc1" placeholder="请输入标签1" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="标签2" path="productTagDesc2" class="form-item">
                    <n-input v-model:value="orderForm.productTagDesc2" placeholder="请输入标签2" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                  <n-form-item label="标签3" path="productTagDesc3" class="form-item">
                    <n-input v-model:value="orderForm.productTagDesc3" placeholder="请输入标签3" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">数值信息</h4>
                <div class="form-row">

                  <n-form-item label="商品价格" path="productPrice" class="form-item">
                    <n-input-number v-model:value="orderForm.productPrice" placeholder="请输入商品价格" :precision="2"
                      class="modern-input total-amount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>

                  <n-form-item label="商品折扣" path="productDiscount" class="form-item">
                    <n-input-number v-model:value="orderForm.productDiscount" placeholder="请输入商品折扣" :precision="2"
                      class="modern-input total-amount">
                      <template #prefix>%</template>
                    </n-input-number>
                  </n-form-item>

                </div>
                <div class="form-row">

                  <n-form-item label="付款人数" path="productPay" class="form-item">
                    <n-input-number v-model:value="orderForm.productPay" placeholder="请输入付款人数" :min="1"
                      class="modern-input" />
                  </n-form-item>

                  <n-form-item label="库存数量" path="stock" class="form-item">
                    <n-input-number v-model:value="orderForm.stock" placeholder="请输入库存" :min="1" class="modern-input" />
                  </n-form-item>

                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">分类与权限</h4>
                <div class="form-row">

                  <n-form-item label="商品权限" path="productAuthority" class="form-item">
                    <n-select v-model:value="orderForm.productAuthority" placeholder="请选择商品权限" :options="statusOptions"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>

                  <n-form-item label="是否上架" path="productRacking" class="form-item">
                    <n-select v-model:value="orderForm.productRacking" placeholder="请选择是否上架"
                      :options="productRackingOptions" :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>

                <div class="form-row">
                  <n-form-item label="商品分类" path="productType" class="form-item">
                    <n-select v-model:value="orderForm.productType" placeholder="请选择商品分类" :options="productTypeOptions"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                  <n-form-item class="form-item" />
                </div>

              </div>

              <div class="form-section">
                <h4 class="section-title">头像</h4>
                <n-upload ref="registerAvatorUploadRef" list-type="image-card" :max="1" :custom-request="handleUpload"
                  @remove="handleRemove" :file-list="avatarFiles" @change="handleFileChange">
                  <n-upload-dragger>
                    <div class="upload-tips">
                      <n-icon size="24" depth="3">
                        <EyeOutline />
                      </n-icon><br />
                      <n-text depth="3" style="font-size: 10px;color: red;">点击或拖拽</n-text><br />
                      <n-p depth="3" style="margin: 0 0; font-size: 10px;color: red;">勿传敏感信息</n-p>
                    </div>
                  </n-upload-dragger>

                  <template #file="{ file }">
                    <n-image :src="file.url" :alt="file.name" width="100" height="100" object-fit="cover"
                      preview-disabled>
                      <template #placeholder>
                        <n-spin size="small" />
                      </template>
                    </n-image>
                  </template>
                </n-upload>
              </div>

            </div>
          </n-form>
        </div>
      </template>


      <template #action>
        <div class="modal-actions">
          <n-space v-if="modalMode !== 'view'" size="medium">
            <n-button @click="cancelOrderModal" class="cancel-btn">取消</n-button>
            <n-button type="primary" @click="confirmOrderModal('add')" :loading="submitLoading" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <AddOutline v-if="modalMode === 'add'" />
                  <CreateOutline v-else />
                </n-icon>
              </template>
              {{ modalMode === 'add' ? '新增商品' : '保存修改' }}
            </n-button>
          </n-space>
          <n-space v-else size="medium">
            <n-button @click="cancelOrderModal" class="cancel-btn">
              关闭
            </n-button>
            <n-button type="primary" @click="switchToEditMode" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <CreateOutline />
                </n-icon>
              </template>
              编辑商品
            </n-button>
          </n-space>
        </div>
      </template>
    </n-modal> -->




    <!-- 查看订单弹窗 -->
    <!-- <n-modal v-model:show="showViewModal" :mask-closable="false" preset="card" title="查看商品信息" class="modern-modal"
      :style="{ width: '800px' }" :auto-focus="false" :close-on-esc="false" transform-origin="center">
      <template #header>
        <div class="modal-header">
          <div class="modal-title-wrapper">
            <n-icon size="24" class="modal-icon">
              <EyeOutline />
            </n-icon>
            <div class="modal-title-text">
              <h3>查看商品</h3>
              <p class="modal-subtitle">查看商品详情</p>
            </div>
          </div>
        </div>
      </template>

      <template #default>
        <div class="modal-content">
          <n-form ref="orderFormRef" :model="orderForm" label-placement="top" class="modern-form" disabled>
            <div class="form-grid">
              <div class="form-section">
                <h4 class="section-title">基本信息</h4>
                <div class="form-row">
                  <n-form-item label="商品ID" path="id" class="form-item">
                    <n-input v-model:value="orderForm.id" placeholder="请输入商品ID" class="modern-input" :disabled="true" />
                  </n-form-item>
                  <n-form-item label="商品名称" path="productName" class="form-item">
                    <n-input v-model:value="orderForm.productName" placeholder="请输商品名" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="商品描述" path="productDesc" class="form-item">
                    <n-input v-model:value="orderForm.productDesc" placeholder="请输入商品描述" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                  <n-form-item label="标签1" path="productTagDesc1" class="form-item">
                    <n-input v-model:value="orderForm.productTagDesc1" placeholder="请输入标签1" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="标签2" path="productTagDesc2" class="form-item">
                    <n-input v-model:value="orderForm.productTagDesc2" placeholder="请输入标签2" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                  <n-form-item label="标签3" path="productTagDesc3" class="form-item">
                    <n-input v-model:value="orderForm.productTagDesc3" placeholder="请输入标签3" class="modern-input"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">数值信息</h4>
                <div class="form-row">

                  <n-form-item label="商品价格" path="productPrice" class="form-item">
                    <n-input-number v-model:value="orderForm.productPrice" placeholder="请输入商品价格" :precision="2"
                      class="modern-input total-amount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>

                  <n-form-item label="商品折扣" path="productDiscount" class="form-item">
                    <n-input-number v-model:value="orderForm.productDiscount" placeholder="请输入商品折扣" :precision="2"
                      class="modern-input total-amount">
                      <template #prefix>%</template>
                    </n-input-number>
                  </n-form-item>

                </div>
                <div class="form-row">

                  <n-form-item label="付款人数" path="productPay" class="form-item">
                    <n-input-number v-model:value="orderForm.productPay" placeholder="请输入付款人数" :min="1"
                      class="modern-input" />
                  </n-form-item>

                  <n-form-item label="库存数量" path="stock" class="form-item">
                    <n-input-number v-model:value="orderForm.stock" placeholder="请输入库存" :min="1" class="modern-input" />
                  </n-form-item>

                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">分类与权限</h4>
                <div class="form-row">

                  <n-form-item label="商品权限" path="productAuthority" class="form-item">
                    <n-select v-model:value="orderForm.productAuthority" placeholder="请选择商品权限" :options="statusOptions"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>

                  <n-form-item label="是否上架" path="productRacking" class="form-item">
                    <n-select v-model:value="orderForm.productRacking" placeholder="请选择是否上架"
                      :options="productRackingOptions" :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                </div>

                <div class="form-row">
                  <n-form-item label="商品分类" path="productType" class="form-item">
                    <n-select v-model:value="orderForm.productType" placeholder="请选择商品分类" :options="productTypeOptions"
                      :disabled="modalMode === 'view'" clearable />
                  </n-form-item>
                  <n-form-item class="form-item" />
                </div>

              </div>

              <div class="form-section">
                <h4 class="section-title">商品图片</h4>
                <n-image :src="orderForm.productImgUrl" alt="商品图片" width="100" height="100" object-fit="cover"
                  preview-disabled>
                  <template #placeholder>
                    <n-spin size="small" />
                  </template>
                </n-image>
              </div>

            </div>
          </n-form>
        </div>
      </template>

      <template #action>
        <div class="modal-actions">
          <n-space size="medium">
            <n-button @click="cancelViewModal" class="cancel-btn">
              关闭
            </n-button>
            <n-button type="primary" @click="switchToEditMode" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <CreateOutline />
                </n-icon>
              </template>
              编辑订单
            </n-button>
          </n-space>
        </div>
      </template>
    </n-modal> -->


    <!-- 编辑订单弹窗 -->
    <n-modal v-model:show="showEditModal" :mask-closable="false" preset="card" title="编辑用户信息" class="modern-modal"
      :style="{ width: '800px' }" :auto-focus="false" :close-on-esc="false" transform-origin="center">
      <template #header>
        <div class="modal-header">
          <div class="modal-title-wrapper">
            <n-icon size="24" class="modal-icon">
              <CreateOutline />
            </n-icon>
            <div class="modal-title-text">
              <h3>编辑用户</h3>
              <p class="modal-subtitle">修改用户信息</p>
            </div>
          </div>
        </div>
      </template>

      <template #default>
        <div class="modal-content">
          <n-form ref="editrFormRef" :model="orderForm" :rules="orderFormRules" label-placement="top"
            class="modern-form">
            <div class="form-grid">
              <div class="form-section">
                <h4 class="section-title">基本信息</h4>
                <div class="form-row">
                  <n-form-item label="用户ID" path="id" class="form-item">
                    <n-input v-model:value="orderForm.id" class="modern-input" :disabled="true" />
                  </n-form-item>
                  <n-form-item label="用户名" path="uname" class="form-item">
                    <n-input v-model:value="orderForm.uname" placeholder="请输入用户名" class="modern-input" clearable />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="密码" path="acrossNum" class="form-item">
                    <n-input v-model:value="orderForm.acrossNum" placeholder="请输入密码" class="modern-input" clearable />
                  </n-form-item>
                  <n-form-item label="账户金额" path="bAccount" class="form-item">
                    <n-input-number v-model:value="orderForm.bAccount" placeholder="请输入商品价格" :precision="4"
                      class="modern-input total-amount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>

                </div>
              </div>

              <!-- <div class="form-section">
                <h4 class="section-title">数值信息</h4>
                <div class="form-row">

                  

                  <n-form-item label="商品折扣" path="productDiscount" class="form-item">
                    <n-input-number v-model:value="orderForm.productDiscount" placeholder="请输入商品折扣" :precision="2"
                      class="modern-input total-amount">
                      <template #prefix>%</template>
                    </n-input-number>
                  </n-form-item>

                </div>
                <div class="form-row">

                  <n-form-item label="付款人数" path="productPay" class="form-item">
                    <n-input-number v-model:value="orderForm.productPay" placeholder="请输入付款人数" :min="1"
                      class="modern-input" />
                  </n-form-item>

                  <n-form-item label="库存数量" path="stock" class="form-item">
                    <n-input-number v-model:value="orderForm.stock" placeholder="请输入库存" :min="1" class="modern-input" />
                  </n-form-item>

                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">分类与权限</h4>
                <div class="form-row">

                  <n-form-item label="商品权限" path="productAuthority" class="form-item">
                    <n-select v-model:value="orderForm.productAuthority" placeholder="请选择商品权限" :options="statusOptions"
                      clearable />
                  </n-form-item>

                  <n-form-item label="是否上架" path="productRacking" class="form-item">
                    <n-select v-model:value="orderForm.productRacking" placeholder="请选择是否上架"
                      :options="productRackingOptions" clearable />
                  </n-form-item>
                </div>

                <div class="form-row">
                  <n-form-item label="商品分类" path="productType" class="form-item">
                    <n-select v-model:value="orderForm.productType" placeholder="请选择商品分类" :options="productTypeOptions"
                      clearable />
                  </n-form-item>
                  <n-form-item class="form-item" />
                </div>

              </div>

              <div class="form-section">
                <h4 class="section-title">重新上传商品图片</h4>
                <div class="form-row">
                  <n-upload ref="registerAvatorUploadRef" list-type="image-card" :max="1" :custom-request="handleUpload"
                    @remove="handleRemove" :file-list="avatarFiles" @change="handleFileChange">
                    <n-upload-dragger>
                      <div class="upload-tips">
                        <n-icon size="24" depth="3">
                          <EyeOutline />
                        </n-icon><br />
                        <n-text depth="3" style="font-size: 10px;color: red;">点击或拖拽</n-text><br />
                        <n-p depth="3" style="margin: 0 0; font-size: 10px;color: red;">勿传敏感信息</n-p>
                      </div>
                    </n-upload-dragger>

                    <template #file="{ file }">
                      <n-image :src="file.url" :alt="file.name" width="100" height="100" object-fit="cover"
                        preview-disabled>
                        <template #placeholder>
                          <n-spin size="small" />
                        </template>
                      </n-image>
                    </template>
                  </n-upload>
                </div>

              </div>

              <div class="form-section">
                <h4 class="section-title">原始商品图片</h4>
                <n-image :src="orderForm.productImgUrl" alt="原始商品图片" width="100" height="100" object-fit="cover">
                  <template #placeholder>
                    <n-spin size="small" />
                  </template>
                </n-image>
              </div> -->

            </div>
          </n-form>
        </div>
      </template>

      <template #action>
        <div class="modal-actions">
          <n-space size="medium">
            <n-button @click="cancelEditModal" class="cancel-btn">
              取消
            </n-button>
            <n-button type="primary" @click="confirmEditModal()" :loading="submitLoading" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <CreateOutline />
                </n-icon>
              </template>
              保存修改
            </n-button>
          </n-space>
        </div>
      </template>
    </n-modal>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import { useMessage, useDialog, FormInst, FormRules, InputInst, useNotification, UploadFileInfo } from 'naive-ui'
import { NButton, NTag, NImage, NSwitch, zhCN, dateZhCN } from 'naive-ui'
import {
  SearchOutline,
  RefreshOutline,
  AddOutline,
  DownloadOutline,
  CreateOutline,
  TrashOutline,
  EyeOutline,
} from '@vicons/ionicons5'
import PageLayout from '@/components/PageLayout.vue'
import { v4 as uuidv4 } from 'uuid';

import { userAPI } from '@/api/user'
import { request } from '@/utils/request'


// 添加组件名称
defineOptions({
  name: 'ProductManagement'
})

const message = useMessage()
const dialog = useDialog()
const loading = ref(false)

// 行选中相关
const checkedRowKeys = ref<string[]>([])
const selectedRows = ref<any[]>([])

// 头像
const registerAvatorUploadRef = ref(null) // 头像上传

// 处理行选中变化
const handleCheckedRowKeysChange = (keys: string[]) => {
  checkedRowKeys.value = keys
  selectedRows.value = tableData.value.filter(item => keys.includes(item.orderId))
}

// 获取行类名
const getRowClassName = (row: any) => {
  if (checkedRowKeys.value.includes(row.orderId)) {
    return 'rainbow-selected-row'
  }
  return ''
}

// 价格格式化方法
const formatPrice = (value, field) => {
  // 处理整数部分（新增时只允许整数）
  if (modalMode.value === 'add' && field === 'productPrice') {
    searchForm.value[field] = Math.floor(value);
  } else {
    // 确保保留两位小数
    const numValue = parseFloat(value);
    if (!isNaN(numValue)) {
      searchForm.value[field] = parseFloat(numValue.toFixed(2));
    }
  }
};



// 处理行点击事件
const handleRowClick = (row: any, index: number) => {
  const rowKey = row.orderId
  const currentIndex = checkedRowKeys.value.indexOf(rowKey)

  if (currentIndex > -1) {
    // 如果当前行已选中，则取消选中
    checkedRowKeys.value.splice(currentIndex, 1)
  } else {
    // 如果当前行未选中，则选中
    checkedRowKeys.value.push(rowKey)
  }

  // 更新选中的行数据
  selectedRows.value = tableData.value.filter(item => checkedRowKeys.value.includes(item.orderId))

  // 打印日志方便调试
  console.log('点击行:', row.orderId, '当前选中:', checkedRowKeys.value)
}

const getDataParam = reactive({
  orderId: '', // 订单号
  orderName: '', // 订单名称
  orderProductId: '', // 订单商品ID
  orderDes: '', // 订单描述
  orderProductPrice: '', // 订单商品单价
  orderSum: '', // 订单总价
  orderTotal: '', // 下单数
  orderProductImg: '', // 商品图片链接
  orderType: '', // 订单状态
  orderByUser: '', // 下单人ID
  orderByUserName: '', // 下单人姓名
  orderByUserTel: '', // 下单人电话
  orderByUserOtherInfo: '', // 订单附加信息
  orderCommand: '', // 订单口令
  OrderCreateTime: '', // 下单时间
  orderOperateTm: '', // 订单处理完成时间
  pageSize: 10, // 每页条数
  currentPage: 1, // 当前页数
})

// 弹窗相关
const showOrderModal = ref(false) // 新增弹窗
const showViewModal = ref(false) // 查看弹窗
const showEditModal = ref(false) // 编辑弹窗

const modalMode = ref<'add' | 'edit' | 'view'>('add')
const modalTitle = computed(() => {
  const titles = {
    add: '新增用户',
    edit: '编辑用户信息',
    view: '查看用户信息'
  }
  return titles[modalMode.value]
})
const submitLoading = ref(false)
const orderFormRef = ref<FormInst | null>(null)
const editrFormRef = ref<FormInst | null>(null)
const addProductFormRef = ref<FormInst | null>(null)


// 订单表单
const orderForm = ref({
  id: '',// 唯一的32位的
  uname: '',// 用户名
  avatarUrl: '',// 头像minio链接
  acrossNum: '',// 密码
  encryptPwd: '',// 加密后的密码
  encryptionAlgorithm: '',// 加密算法
  email: '',// 电子邮件
  telNum: '',// 电话号码
  wechatAbt: '',// 微信相关信息
  roleNum: '',// 角色编号
  freezeOrnnt: '',// 是否冻结 0 不冻结 1 冻结
  createTm: '',// 创建时间 timestamp格式
  updateTm: '',// 最新修改时间timestamp格式
  accountMoney: 0.00,// 账户金额
  bAccount: 0.0000,// 账户金额
})

// 新增商品表单校验规则
const productFormRules: FormRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  productPrice: [
    { required: true },
    { validator: (rule: any, value: number) => value > 0, message: '价格必须大于0', trigger: 'blur' }
  ],
  stock: [
    { required: true },
    { validator: (rule: any, value: number) => value > 0, message: '价格必须大于0', trigger: 'blur' }
  ],
  productAuthority: [
    {
      required: true,
      validator: (rule: any, value: number) => {
        return [999, 0, 1, 2, 3, 4, 5].includes(value);
      },
      message: '请选择商品权限',
      trigger: ['change', 'blur']
    }
  ],
  productRacking: [
    {
      required: true,
      validator: (rule: any, value: number) => {
        return [0, 1].includes(value);
      },
      message: '请选择是否上架',
      trigger: ['change', 'blur']
    }
  ],
  productType: [
    {
      required: true,
      // 自定义校验函数，明确判断 0 是有效值
      validator: (rule: any, value: number) => {
        // 允许的值为 0/1/2/3/4（与选项值对应）
        return [0, 1, 2, 3, 4].includes(value);
      },
      message: '请选择商品分类',
      trigger: ['change', 'blur'] // 增加 blur 触发，提高校验灵敏度
    }
  ],

}

const imageValidationRules = {
  // 允许的图片格式（根据业务需求调整）
  allowedTypes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
  allowedExtensions: ['jpg', 'jpeg', 'png', 'webp', 'gif'], // 用于后缀名校验
  maxSize: 10 * 1024 * 1024, // 最大5MB（单位：字节）
  maxCount: 1 // 最大上传数量（你的代码中已限制为1）
};

// 错误提示信息
const imageErrorMessages = {
  typeError: `请上传以下格式的图片：${imageValidationRules.allowedExtensions.join('、')}`,
  sizeError: `图片大小不能超过${imageValidationRules.maxSize / 1024 / 1024}MB`,
  countError: `最多只能上传${imageValidationRules.maxCount}张图片`,
  requiredError: '请上传商品图片' // 如果图片为必填项
};

// 表单验证规则
const orderFormRules: FormRules = {
  // 客户ID
  orderByUser: [
    { required: true, message: '请输入客户ID', trigger: 'blur' }
  ],
  // 客户账号
  orderByUserName: [
    { required: true, message: '请输入客户账号', trigger: 'blur' }
  ],
  // 商品ID
  orderProductId: [
    { required: true, message: '请输入商品ID', trigger: 'blur' }
  ],
  // 商品名称
  orderProductName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  // 数量
  // orderTotal: [
  //   { required: true, message: '请输入数量', trigger: 'blur' },
  //   // { validator: (rule: any, value: number) => value >= 1, message: '数量必须大于0', trigger: 'blur' }
  // ],
  // 订单状态
  // orderType: [
  //   { required: true, message: '请选择订单状态', trigger: 'blur' }
  // ],
  // 备注信息
  // orderByUserOtherInfo: [
  //   { required: true, message: '请输入备注信息', trigger: 'blur' }
  // ],


  // orderNumber: [
  //   { required: true, message: '请输入订单号', trigger: 'blur' }
  // ],
  // customerName: [
  //   { required: true, message: '请输入客户姓名', trigger: 'blur' }
  // ],
  // productName: [
  //   { required: true, message: '请输入商品名称', trigger: 'blur' }
  // ],
  // quantity: [
  //   { required: true, message: '请输入数量', trigger: 'blur' },
  //   { validator: (rule: any, value: number) => value >= 1, message: '数量必须大于0', trigger: 'blur' }
  // ],
  // price: [
  //   { required: true, message: '请输入单价', trigger: 'blur' },
  //   { validator: (rule: any, value: number) => value >= 0, message: '单价不能小于0', trigger: 'blur' }
  // ],
  // status: [
  //   { required: true, message: '请选择订单状态', trigger: 'change' }
  // ]
}

// 搜索表单
const searchForm = ref({
  id: '',// 唯一的32位的
  uname: '',// 用户名
  avatarUrl: '',// 头像minio链接
  acrossNum: '',// 密码
  encryptPwd: '',// 加密后的密码
  encryptionAlgorithm: '',// 加密算法
  email: '',// 电子邮件
  telNum: '',// 电话号码
  wechatAbt: '',// 微信相关信息
  roleNum: '',// 角色编号
  freezeOrnnt: '',// 是否冻结 0 不冻结 1 冻结
  createTm: '',// 创建时间 timestamp格式
  updateTm: '',// 最新修改时间timestamp格式
  accountMoney: 0.00,// 账户金额
  bAccount: 0.0000,// 账户金额
})

// 商品商家状态
const productRackingOptions = [
  { label: '已上架', value: 1 },
  { label: '已下架', value: 0 },
]

// 是否冻结
const productFreezeOptions = [
  { label: '未冻结', value: 0 },
  { label: '已冻结', value: 1 },
]

// 商品分类
const productTypeOptions = [
  { label: '咸鱼', value: 0 },
  { label: '抖音', value: 1 },
  { label: '小红书', value: 2 },
  { label: '视频号', value: 3 },
  { label: '快手', value: 4 },
]

// 状态选项 - 修改为数字状态值
const statusOptions = [
  { label: '超级管理员', value: 999 },
  { label: '游客', value: 0 },
  { label: '注册用户', value: 1 },
  { label: '一级代理', value: 2 },
  { label: '二级代理', value: 3 },
  { label: '三级代理', value: 4 },
  { label: '四级代理', value: 5 },
]

// 根据模式动态获取状态选项
const currentStatusOptions = computed(() => {
  if (modalMode.value === 'add') {
    // 新增时只显示待处理选项
    return [{ label: '待处理', value: 0 }]
  } else if (modalMode.value === 'edit') {
    // 编辑时显示除了"已删除"之外的所有选项
    return statusOptions.filter(option => option.value !== 4)
  } else {
    // 查看时显示全部选项
    return statusOptions
  }
})

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

const UUID = () => {
  return uuidv4().replace(/-/g, '').substring(0, 32)
}

// 通过商品ID 或者商品名字  获取商品信息
const getProductById = async () => {
  // console.log("getProductByIdgetProductByIdgetProductById", orderForm.value.orderProductId)
  // if (orderForm.value.orderProductId !== '' || orderForm.value.orderProductName !== '') {
  //   const res = await orderAPI.getProductInfoById({
  //     id: orderForm.value.orderProductId,
  //     product_name: orderForm.value.orderProductName.replace("购买: ", ''),
  //   })
  //   console.log('✅ 根据商品ID查询商品信息:', res)
  //   if (res.code === 200 && res.msg === '查询商品信息成功') {
  //     orderForm.value.orderProductId = res.data.id
  //     orderForm.value.orderProductImg = res.data.product_img_url
  //     orderForm.value.orderProductPrice = res.data.product_price
  //     orderForm.value.orderName = "购买: " + res.data.product_name
  //     orderForm.value.orderProductName = res.data.product_name
  //   } else {
  //     orderForm.value.orderProductName = ''
  //     orderForm.value.orderProductId = ''
  //     message.warning('商品不存在')

  //   }
  // }

}



// 通过用户ID 或者 账号名 或者 用户电话 获取用户信息
const getUserInfoById = async () => {
  console.log("getUserInfoByIdgetUserInfoByIdgetUserInfoByIdgetUserInfoById")
  // if (
  //   orderForm.value.orderByUser !== '' ||
  //   orderForm.value.orderByUserName !== '' ||
  //   orderForm.value.orderByUserTel !== ''
  // ) {
  //   const res = await orderAPI.getUserInfoByIdOrNameOrTel({
  //     usrId: orderForm.value.orderByUser,
  //     uName: orderForm.value.orderByUserName,
  //     uCellphone: orderForm.value.orderByUserTel,
  //   })
  //   console.log('✅ 通过用户ID 或者 账号名 或者 用户电话 获取用户信息:', res)
  //   if (res.code === 200 && res.msg === '用户信息查询成功') {
  //     orderForm.value.orderByUser = res.data.usrId
  //     orderForm.value.orderByUserName = res.data.uName
  //     orderForm.value.orderByUserTel = res.data.uCellphone
  //   } else {
  //     orderForm.value.orderByUser = ''
  //     orderForm.value.orderByUserName = ''
  //     orderForm.value.orderByUserTel = ''
  //     message.warning('未查询到用户信息')

  //   }
  // }

}










// ======================= 上传头像 =======================
const isUploadAvatarDone = ref(false); //头像是否上传成功
const avatarFiles = ref<UploadFileInfo[]>([]);
const showloading = ref(false);

// 文件状态变化处理
const handleFileChange = (options: { file: UploadFileInfo, fileList: UploadFileInfo[] }) => {
  avatarFiles.value = options.fileList;
};

// 独立生成器函数
function generateUniqueName(ext: string, username: string) {
  const timestamp = (Date.now() - new Date('2024-01-01').getTime())
    .toString(36)
    .toUpperCase();
  const randomPart = Math.random().toString(36).slice(2, 6);
  // return `${timestamp}_${randomPart}.${ext}`;
  return `${username}.${ext}`;
}

// 上传处理
const handleUpload = async (options: { file: UploadFileInfo }) => {
  // console.log(options)
  try {
    // 文件存在性检查
    if (!options?.file || !(options.file.file instanceof File)) {
      throw new Error('未选择有效文件');
    }

    const file = options.file.file as File;
    // 2. 校验文件类型（MIME类型）
    if (!imageValidationRules.allowedTypes.includes(file.type)) {
      message.error(imageErrorMessages.typeError);
      // 清空无效文件
      avatarFiles.value = [];
      return;
    }

    // 3. 校验文件大小
    if (file.size > imageValidationRules.maxSize) {
      message.error(imageErrorMessages.sizeError);
      avatarFiles.value = [];
      return;
    }

    // 4. 校验文件数量（你的代码中已通过max=1限制，这里做二次确认）
    if (avatarFiles.value.length > imageValidationRules.maxCount) {
      message.error(imageErrorMessages.countError);
      return;
    }

    // 5. 校验文件后缀名（双重保险，防止MIME类型伪造）
    const fileExtension1 = file.name.split('.').pop()?.toLowerCase();
    if (!fileExtension1 || !imageValidationRules.allowedExtensions.includes(fileExtension1)) {
      message.error(imageErrorMessages.typeError);
      avatarFiles.value = [];
      return;
    }

    // 校验文件后缀
    const initialValues = ['bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd',
      'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp', 'avif', 'apng'];
    const safeAvatarFilename = ref(new Set(initialValues));
    const lastDotIndex = options.file.name.lastIndexOf('.');
    const fileSuffix = (lastDotIndex > 0) ? options.file.name.substring(lastDotIndex + 1) : '';
    if (!safeAvatarFilename.value.has(fileSuffix)) {
      message.error("请上传安全的头像文件!");
      avatarFiles.value = [];
      return;
    }

    // 文件名生成逻辑 --------------------------------------------------------
    const originalFile = options.file.file as File;
    const fileExtension = originalFile.name.split('.').pop() || 'png';
    // 将用户名作为头像文件名（用户名不重复的）
    const sanitizedName = generateUniqueName(fileExtension, UUID());
    // 创建新文件对象
    const modifiedFile = new File([originalFile], sanitizedName, { type: originalFile.type });
    // 更新上传文件引用
    options.file.file = modifiedFile;
    options.file.name = sanitizedName;
    // ------------------------------------------------------------------------
    const formData = new FormData();
    formData.append('avatar', options.file.file as File);
    formData.append('userId', UUID());

    // 显示上传进度
    options.file.status = 'uploading';
    options.file.percentage = 10;
    showloading.value = true
    const res = await request.upload<{ url: string }>(
      "/api/uploadProductImg",
      options.file.file,
      { userId: UUID() }, // 可添加额外参数
      { headers: { 'X-Upload-Type': 'avatar' } },
      { fieldName: 'avatar' } // 和后端 @RequestParam 名称保持一致
    );
    console.log("商品图片上传", res)
    if (res.code === 200) {
      message.success("商品图片上传成功!");
      options.file.status = 'finished';
      // @ts-ignore
      options.file.url = res.data; // 显示缩略图
      // @ts-ignore
      orderForm.value.productImgUrl = res.data
      isUploadAvatarDone.value = true;
      showloading.value = false
    }

  } catch (error) {
    options.file.status = 'error';
    message.error(`商品图片上传失败: ${(error as Error).message}`);
  }
};

// 删除处理（完整版）
const handleRemove = async (options: { file: UploadFileInfo }) => {

  try {
    const fileName = orderForm.value.productImgUrl.split('/').pop()
    console.log("删除文件", fileName)
    // 调用后端删除接口
    const res = await productAPI.deleteProductImg({ productImgUrl: fileName })
    console.log(res)
    if (res.code === 200 && res.data) {
      isUploadAvatarDone.value = false;
      avatarFiles.value = [];
      orderForm.value.productImgUrl = ''
      message.info('商品图片已删除');
    } else {
      message.error('商品图片删除失败，请联系管理员');
    }

  } catch (error) {
    message.error(`商品图片失败: ${(error as Error).message}`);
  }
};
// ======================= 上传头像 =======================










// 处理订单开关切换
const handleProcessSwitch = async (row: any, value: boolean) => {
  try {
    // 确定新状态：开启为处理中(1)，关闭为待处理(0)
    const newStatus = value ? '1' : '0'

    // 更新本地数据
    const index = allData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      allData.value[index].freezeOrnnt = newStatus

      // 更新当前页面显示的数据
      const currentIndex = tableData.value.findIndex(item => item.id === row.id)
      if (currentIndex !== -1) {
        tableData.value[currentIndex].freezeOrnnt = newStatus
      }
    }

    // 这里可以添加API调用来更新后端状态
    console.log({ id: row.id, freezeOrnnt: newStatus })
    const res = await userAPI.updateBakUserType(row)
    console.log(res)
    if (res.code === 200 && res.msg === '用户状态更新成功') {
      const statusText = value ? '账户已冻结' : '账户已启用'
      message.success(`用户  ${row.uname}  ${statusText}`)
      getOrderList(null)
    }



  } catch (error) {
    console.error('更新商品状态失败:', error)
    message.error('更新商品状态失败')
    // 如果更新失败，恢复原状态
    getOrderList(null)
  }
}



// 分页前缀
const paginationPrefix = ({ itemCount }: any) => `共 ${itemCount} 条数据`

// 表格列配置
const columns: any[] = [
  // 选择列
  {
    type: 'selection',
    width: 50,
    fixed: 'left'
  },
  // 用户ID - 左侧固定
  {
    title: '用户ID',
    key: 'id',
    width: 200,
    filterable: true,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', {
      class: 'order-number',
      style: { fontWeight: '600', color: '#1890ff' }
    }, row.id || 'N/A')
  },
  // 用户名
  {
    title: '用户名',
    key: 'uname',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.uname || '无用户名')
  },
  // 用户头像
  {
    title: '用户头像',
    key: 'avatarUrl',
    width: 120,
    render: (row: any) => {
      if (row.avatarUrl) {
        return h(NImage, {
          width: 60,
          height: 60,
          src: row.avatarUrl,
          objectFit: 'cover',
          previewDisabled: false,
          style: 'border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);'
        })
      }
    }
  },
  // 邮箱
  {
    title: '邮箱',
    key: 'email',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.email || '')
  },
  // 电话
  {
    title: '电话',
    key: 'telNum',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.telNum || '')
  },
  // 微信
  {
    title: '微信',
    key: 'wechatAbt',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.wechatAbt || '')
  },
  // 角色
  {
    title: '角色',
    key: 'roleNum',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.roleNum || '')
  },
  //  是否冻结
  {
    title: '是否冻结',
    key: 'freezeOrnnt',
    width: 90,
    align: 'center',
    render: (row: any) => {
      const canOperate = row.freezeOrnnt === '0' || row.freezeOrnnt === '1'
      return h(NSwitch, {
        value: row.freezeOrnnt === '1',
        // disabled: !canOperate,
        disabled: false,
        size: 'small',
        onUpdateValue: (value: boolean) => handleProcessSwitch(row, value)
      })
    }
  },
  // 用户密码
  {
    title: '密码',
    key: 'acrossNum',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.acrossNum || '')
  },
  // 加密密码
  {
    title: '加密密码',
    key: 'encryptPwd',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.encryptPwd || '')
  },
  // 加密算法
  {
    title: '加密算法',
    key: 'encryptionAlgorithm',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.encryptionAlgorithm || '')
  },
  // 商品创建时间
  {
    title: '创建时间',
    key: 'createTm',
    width: 120,
    render: (row: any) => {
      if (!row.createTm) {
        return h('div', { class: 'time-cell' }, [
          h('div', { class: 'time-date' }, '未知日期'),
          h('div', { class: 'time-time' }, '未知时间')
        ])
      }

      const date = new Date(row.createTm)
      const dateStr = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
      const timeStr = date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })

      return h('div', { class: 'time-cell' }, [
        h('div', { class: 'time-date' }, dateStr),
        h('div', { class: 'time-time' }, timeStr)
      ])
    },
    sorter: (row1: any, row2: any) => {
      const time1 = row1.createTm ? new Date(row1.createTm).getTime() : 0
      const time2 = row2.createTm ? new Date(row2.createTm).getTime() : 0
      return time1 - time2
    }
  },

  // 最新修改时间
  {
    title: '更新时间',
    key: 'updateTm',
    width: 120,
    render: (row: any) => {
      if (!row.updateTm) {
        return h('div', { class: 'time-cell' }, [
          h('div', { class: 'time-date' }, '未知日期'),
          h('div', { class: 'time-time' }, '未知时间')
        ])
      }

      const date = new Date(row.updateTm)
      const dateStr = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
      const timeStr = date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })

      return h('div', { class: 'time-cell' }, [
        h('div', { class: 'time-date' }, dateStr),
        h('div', { class: 'time-time' }, timeStr)
      ])
    },
    sorter: (row1: any, row2: any) => {
      const time1 = row1.updateTm ? new Date(row1.updateTm).getTime() : 0
      const time2 = row2.updateTm ? new Date(row2.updateTm).getTime() : 0
      return time1 - time2
    }
  },
  // 账户余额
  {
    title: '账户金额',
    key: 'bAccount',
    width: 100,
    align: 'right',
    render: (row: any) => h('span', {
      class: 'unit-price',
      style: { fontWeight: '600', color: '#fa541c' }
    }, `¥${(row.bAccount || 0).toFixed(4)}`),
    sorter: (row1: any, row2: any) => (row1.bAccount || 0) - (row2.bAccount || 0)
  },
  // 操作按钮 - 右侧固定
  {
    title: '操作',
    key: 'actions',
    width: 50,
    align: 'center',
    fixed: 'right',
    render: (row: any) => {
      const buttons = []
      // buttons.push(h(NButton, {
      //   size: 'small',
      //   type: 'info',
      //   quaternary: true,
      //   onClick: () => handleView(row)
      // }, { default: () => '查看' }))

      // if (row.orderType === 0 || row.orderType === 1) {
      if (true) {
        buttons.push(h(NButton, {
          size: 'small',
          type: 'info',
          quaternary: true,
          style: { marginLeft: '8px' },
          onClick: () => handleEdit(row)
        }, { default: () => '编辑' }))

        // buttons.push(h(NButton, {
        //   size: 'small',
        //   type: 'error',
        //   quaternary: true,
        //   style: { marginLeft: '8px' },
        //   onClick: () => handleDelete(row)
        // }, { default: () => '删除' }))
      }

      return h('div', { class: 'action-buttons' }, buttons)
    }
  }
]

// 表格数据
const tableData = ref<any[]>([])
const allData = ref<any[]>([])

// 获取列表信息
const getOrderList = async (params: any) => {
  try {
    loading.value = true

    // 使用最简单的参数进行测试
    const requestParams = {
      pageSize: pagination.value.pageSize, // 每页条数
      currentPage: pagination.value.page,  // 当前页码

      id: searchForm.value.id,// 唯一的32位的
      uname: searchForm.value.uname,// 用户名
      acrossNum: searchForm.value.acrossNum,// 密码
      encryptPwd: searchForm.value.encryptPwd,// 加密后的密码
      encryptionAlgorithm: searchForm.value.encryptionAlgorithm,// 加密算法
      email: searchForm.value.email,// 电子邮件
      telNum: searchForm.value.telNum,// 电话号码
      wechatAbt: searchForm.value.wechatAbt,// 微信相关信息
      avatarUrl: searchForm.value.avatarUrl,// 头像minio链接
      roleNum: searchForm.value.roleNum,// 角色编号
      freezeOrnnt: searchForm.value.freezeOrnnt,// 是否冻结 0 不冻结 1 冻结
      createTm: searchForm.value.createTm,// 创建时间 timestamp格式
      updateTm: searchForm.value.updateTm,// 最新修改时间timestamp格式
      accountMoney: searchForm.value.accountMoney,// 账户金额
      bAccount: searchForm.value.bAccount,// 账户金额

    }

    console.log('📤 发送请求参数:', requestParams)

    try {

      const res = await userAPI.getBakUserList(requestParams)
      console.log('✅ 用户信息API响应:', res)

      const listCount = await userAPI.getBakUserListCount(requestParams)
      console.log(listCount)

      if (res.code === 200) {
        // 处理新的响应格式
        if (res.data && typeof res.data === 'object') {
          // 如果是 OrderListResponse 格式
          if ('list' in res.data) {
            tableData.value = res.data.list || []
            allData.value = res.data.list || []
            pagination.value.itemCount = listCount.data || 0
          } else if (Array.isArray(res.data)) {
            // 如果直接是数组格式
            tableData.value = res.data
            allData.value = res.data
            pagination.value.itemCount = listCount.data
          } else {
            // 其他格式
            tableData.value = []
            allData.value = []
            pagination.value.itemCount = 0
          }
        } else {
          tableData.value = []
          allData.value = []
          pagination.value.itemCount = 0
        }
      } else {
        console.error('❌ API返回错误:', res)
        message.error(res.msg || res.message || '获取订单列表失败')
        // 清空数据
        tableData.value = []
        allData.value = []
        pagination.value.itemCount = 0
      }

    } catch (apiError: any) {
      console.error('❌ API调用异常:', apiError)
      message.error(`连接后端失败: ${apiError.message || '网络错误'}`)
      // 清空数据
      tableData.value = []
      allData.value = []
      pagination.value.itemCount = 0
    }

  } catch (error: any) {
    console.error('❌ 获取订单失败:', error)
    message.error('获取订单列表失败: ' + (error.message || '网络错误'))
    // 清空数据
    tableData.value = []
    allData.value = []
    pagination.value.itemCount = 0
  } finally {
    loading.value = false
  }
}

// 事件处理
const handleSearch = () => {
  pagination.value.page = 1 // 重置到第一页
  getOrderList(searchForm) // 获取订单列表
}

const handleReset = () => {
  searchForm.value = {
    id: '',// 唯一的32位的
    uname: '',// 用户名
    acrossNum: '',// 密码
    encryptPwd: '',// 加密后的密码
    encryptionAlgorithm: '',// 加密算法
    email: '',// 电子邮件
    telNum: '',// 电话号码
    wechatAbt: '',// 微信相关信息
    avatarUrl: '',// 头像minio链接
    roleNum: '',// 角色编号
    freezeOrnnt: '',// 是否冻结 0 不冻结 1 冻结
    createTm: '',// 创建时间 timestamp格式
    updateTm: '',// 最新修改时间timestamp格式
    accountMoney: 0.00,// 账户金额
    bAccount: 0.0000,// 账户金额
  }
  pagination.value.page = 1 // 重置到第一页
  getOrderList(null) // 重新加载数据
  message.info('已重置搜索条件')
}

const handleRefresh = () => {
  getOrderList(null) // 重新加载数据
  message.info('数据已刷新')
}

// 弹窗相关函数
const resetOrderForm = () => {
  orderForm.value = {
    id: '',// 唯一的32位的
    uname: '',// 用户名
    avatarUrl: '',// 头像minio链接
    acrossNum: '',// 密码
    encryptPwd: '',// 加密后的密码
    encryptionAlgorithm: '',// 加密算法
    email: '',// 电子邮件
    telNum: '',// 电话号码
    wechatAbt: '',// 微信相关信息
    roleNum: '',// 角色编号
    freezeOrnnt: '',// 是否冻结 0 不冻结 1 冻结
    createTm: '',// 创建时间 timestamp格式
    updateTm: '',// 最新修改时间timestamp格式
    accountMoney: 0.00,// 账户金额
    bAccount: 0.0000,// 账户金额
  }
}

// 新增商品
const handleAdd = () => {
  modalMode.value = 'add'
  resetOrderForm()
  // 生成商品ID
  orderForm.value.id = UUID()
  avatarFiles.value = [];
  orderForm.value.avatarUrl = ''
  showOrderModal.value = true
}

const handleView = (row: any) => {
  modalMode.value = 'view'
  console.log("查看商品信息", row)
  // 映射API数据到表单格式
  orderForm.value = {
    id: row.id,// 唯一的32位的
    uname: row.uname,// 用户名
    avatarUrl: row.avatarUrl,// 头像minio链接
    acrossNum: row.acrossNum,// 密码
    encryptPwd: row.encryptPwd,// 加密后的密码
    encryptionAlgorithm: row.encryptionAlgorithm,// 加密算法
    email: row.email,// 电子邮件
    telNum: row.telNum,// 电话号码
    wechatAbt: row.wechatAbt,// 微信相关信息
    roleNum: row.roleNum,// 角色编号
    freezeOrnnt: row.freezeOrnnt,// 是否冻结 0 不冻结 1 冻结
    createTm: row.createTm,// 创建时间 timestamp格式
    updateTm: row.updateTm,// 最新修改时间timestamp格式
    accountMoney: row.accountMoney,// 账户金额
    bAccount: row.bAccount,// 账户金额
  }
  showViewModal.value = true
}

const handleEdit = (row: any) => {
  modalMode.value = 'edit'
  console.log("编辑商品信息")
  // 映射API数据到表单格式
  orderForm.value = {
    id: row.id,// 唯一的32位的
    uname: row.uname,// 用户名
    avatarUrl: row.avatarUrl,// 头像minio链接
    acrossNum: row.acrossNum,// 密码
    encryptPwd: row.encryptPwd,// 加密后的密码
    encryptionAlgorithm: row.encryptionAlgorithm,// 加密算法
    email: row.email,// 电子邮件
    telNum: row.telNum,// 电话号码
    wechatAbt: row.wechatAbt,// 微信相关信息
    roleNum: row.roleNum,// 角色编号
    freezeOrnnt: row.freezeOrnnt,// 是否冻结 0 不冻结 1 冻结
    createTm: row.createTm,// 创建时间 timestamp格式
    updateTm: row.updateTm,// 最新修改时间timestamp格式
    accountMoney: row.accountMoney,// 账户金额
    bAccount: row.bAccount,// 账户金额
  }
  showEditModal.value = true
}

const cancelOrderModal = () => {
  // console.log("关闭弹窗")
  // const fileName = orderForm.value.productImgUrl.split('/').pop()
  // console.log("删除文件", fileName)
  // // 调用后端删除接口
  // if (fileName !== '') {
  //   productAPI.deleteProductImg({ productImgUrl: fileName })
  // }
  // isUploadAvatarDone.value = false;
  // avatarFiles.value = [];
  // orderForm.value.productImgUrl = ''
  // showOrderModal.value = false
  // resetOrderForm()
}

const cancelViewModal = () => {
  showViewModal.value = false
  resetOrderForm()
}

const cancelEditModal = () => {
  showEditModal.value = false
  resetOrderForm()
}

const switchToEditMode = () => {
  showViewModal.value = false
  showEditModal.value = true
}

const confirmOrderModal = async (type: string) => {
  console.log("表单保存 modalMode.value ", modalMode.value)
  console.log("表单保存123 type", type)
  if (!addProductFormRef.value) return
  try {
    await addProductFormRef.value.validate()
    if (!avatarFiles.value.length) {
      message.error(imageErrorMessages.requiredError); // 请上传商品图片
      return; // 阻止表单提交
    }
    await addProductFormRef.value.validate();
    submitLoading.value = true
    // if (modalMode.value === 'add') {



    if (type === 'add') {
      // console.log("创建商品", orderForm.value)
      // const res = await productAPI.productCreateBak(orderForm.value)
      // console.log("新增商品返回结果", res)

      // if (res.code == 200 && res.msg === '商品创建成功' && res.data === 1) {
      //   message.success('商品创建成功')
      //   getOrderList(null) // 重新加载数据
      //   orderForm.value.productImgUrl = ''
      //   showOrderModal.value = false
      //   submitLoading.value = false
      //   return
      // }

    }




    if (type === 'edit') {

      console.log("修改订单", orderForm.value)
      //const res = await orderAPI.orderUpdateBak(orderForm.value)
      //console.log("修改订单返回结果", res)




    }


  } catch (error) {
    submitLoading.value = false
    message.error('保存失败，请联系管理员')
    console.error('保存失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 保存编辑
const confirmEditModal = async () => {
  if (!editrFormRef.value) return

  try {
    await editrFormRef.value.validate()

    submitLoading.value = true

    // 在这里添加编辑订单的API调用
    console.log("confirmEditModal", orderForm.value)
    const res = await userAPI.userUpdateBak(orderForm.value)
    console.log("修改用户信息", res)

    if (res.code == 200 && res.msg === '修改成功' && res.data === 1) {
      message.success('用户信息修改成功')
      submitLoading.value = false // 保存按钮loading
      showEditModal.value = false // 关闭编辑弹窗
      resetOrderForm() // 清空弹窗表单
      getOrderList(null) // 刷新订单列表
    } else {
      message.error('用户信息修改失败，请联系管理员')
      submitLoading.value = false // 保存按钮loading
      showEditModal.value = false // 关闭编辑弹窗
    }

  } catch (error) {
    console.error('表单验证失败:', error)
    submitLoading.value = false
  }
}


const deleteProduct = async (row: any) => {

  try {

    // loading.value = true

    // // 在这里添加编辑订单的API调用
    // console.log("deleteProduct", row)
    // const res = await productAPI.deleteProductByIdBak(row)
    // console.log("删除商品", res)

    // if (res.code === 200 && res.msg === '商品删除成功') {
    //   getOrderList(null) // 刷新列表
    //   loading.value = false
    //   message.success('商品删除成功！')
    // }



  } catch (error) {
    console.error('订单删除失败:', error)
    message.error('删除订单失败,请联系管理员')
    loading.value = false
  } finally {
    loading.value = false
  }
}



const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除订单 \n  【${row.productName || row.id}】 吗？\n 删除后数据永久消失无备份！`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: () => {
      const index = allData.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        allData.value.splice(index, 1)
        pagination.value.itemCount = allData.value.length
        // 重新处理分页显示
        const startIndex = (pagination.value.page - 1) * pagination.value.pageSize
        const endIndex = startIndex + pagination.value.pageSize
        tableData.value = allData.value.slice(startIndex, endIndex)
        console.log("删除订单按钮", row)
        loading.value = true // 表格loading
        deleteProduct(row) // 调用后台删除商品
        message.success('删除商品成功')
      }
    }
  })
}

const handleExport = () => {
  message.info('导出数据功能')
}

const handlePageChange = (page: number) => {
  pagination.value.page = page
  getOrderList(null) // 重新加载数据
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  pagination.value.page = 1
  getOrderList(null) // 重新加载数据
}

const testAPI = async () => {
  try {
    console.log('🔍 开始测试API连接...')
    message.info('正在测试API连接...')

    // 最简单的测试参数
    const testParams = {
      pageSize: 10,
      currentPage: 1
    }

    console.log('📤 测试参数:', testParams)

    // 直接使用fetch测试，绕过axios
    const response = await fetch('/api/orderListBak', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(testParams)
    })

    console.log('📊 Fetch响应状态:', response.status)
    console.log('📊 Fetch响应头:', response.headers)

    if (response.ok) {
      const data = await response.json()
      console.log('📊 Fetch响应数据:', data)
      message.success('✅ API连接成功！')
    } else {
      const errorText = await response.text()
      console.error('❌ API响应错误:', errorText)
      message.error(`❌ API返回错误: ${response.status}`)
    }

  } catch (error) {
    console.error('❌ API测试失败:', error)
    message.error(`❌ 连接失败: ${error.message}`)
  }
}

onMounted(() => {
  // 页面加载时获取订单列表（如果API失败会自动加载模拟数据）
  getOrderList(null)
})


</script>

<style scoped>
/* 头像 */
.upload-tips {
  padding: 12px;
  text-align: center;
}

.page-container {
  padding: var(--spacing-lg);
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-color-secondary);
}

.search-card {
  flex-shrink: 0;
  margin-bottom: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
}

.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-header-section {
  flex-shrink: 0;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-bottom: none;
  border-radius: 12px 12px 0 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color-primary);
}

.table-content {
  flex: 1;
  overflow: hidden;
  border-left: 1px solid var(--border-color-primary);
  border-right: 1px solid var(--border-color-primary);
  background: var(--bg-color-primary);
  min-height: 50%;
  max-height: 100%;
}

.table-data-area {
  flex: 1;
  overflow: auto;
  height: 100%;
  padding-bottom: 0px;
}

/* 🔧 表格基础样式 - 专业级滚动配置 */
.data-table {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 表格包装器 - 核心滚动配置 */
.data-table :deep(.n-data-table-wrapper) {
  border-radius: 8px;
  height: 100%;
}

/* 表格基础容器 */
.data-table :deep(.n-data-table) {
  height: 100%;
  /* 让Naive UI处理所有滚动逻辑 */
}

/* 表头样式 - 确保固定功能正常 */
.data-table :deep(.n-data-table-th) {
  background-color: #fafafa !important;
  font-weight: 600;
  font-size: 14px;
  color: #262626;
  border-bottom: 2px solid #e8e8e8;
  padding: 16px 12px;
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 10;
}

/* 表格单元格样式 */
.data-table :deep(.n-data-table-td) {
  padding: 12px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 15px;
  font-weight: 500;
  line-height: 1.6;
  letter-spacing: 0.3px;
  color: #2c3e50;
  border-bottom: 1px solid #f0f0f0;
  vertical-align: top;
  position: relative;
  z-index: 1;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

/* 固定列样式 - 确保固定列正常显示 */
.data-table :deep(.n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-td.n-data-table-td--fixed-right) {
  position: sticky !important;
  z-index: 10 !important;
  background: var(--n-td-color) !important;
}

/* 固定列在悬浮时的背景处理 */
.data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 固定列在选中时的背景处理 */
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 表格行悬停效果 - 动态渐变效果 */
.data-table :deep(.n-data-table-tr) {
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.data-table :deep(.n-data-table-tr:hover) {
  background-color: rgba(0, 0, 0, 0.02);
}

.data-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.2) 0%,
      rgba(255, 165, 0, 0.2) 12.5%,
      rgba(255, 255, 0, 0.2) 25%,
      rgba(0, 255, 0, 0.2) 37.5%,
      rgba(0, 255, 255, 0.2) 50%,
      rgba(0, 0, 255, 0.2) 62.5%,
      rgba(75, 0, 130, 0.2) 75%,
      rgba(238, 130, 238, 0.2) 87.5%,
      rgba(255, 0, 0, 0.2) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.1);
  z-index: 0;
}

.data-table :deep(.n-data-table-tr:hover .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

/* 选中行的彩虹色动态渐变效果 */
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.25) 0%,
      rgba(255, 165, 0, 0.25) 12.5%,
      rgba(255, 255, 0, 0.25) 25%,
      rgba(0, 255, 0, 0.25) 37.5%,
      rgba(0, 255, 255, 0.25) 50%,
      rgba(0, 0, 255, 0.25) 62.5%,
      rgba(75, 0, 130, 0.25) 75%,
      rgba(238, 130, 238, 0.25) 87.5%,
      rgba(255, 0, 0, 0.25) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.2);
  z-index: 0;
}

.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

@keyframes rainbowMove {
  0% {
    background-position: 0% 50%;
  }

  25% {
    background-position: 100% 50%;
  }

  50% {
    background-position: 200% 50%;
  }

  75% {
    background-position: 300% 50%;
  }

  100% {
    background-position: 400% 50%;
  }
}

/* 时间显示样式 */
.time-cell {
  line-height: 1.5;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
}

.time-date {
  font-weight: 600;
  font-size: 14px;
  color: #1a202c;
  margin-bottom: 3px;
  letter-spacing: 0.2px;
}

.time-time {
  font-size: 13px;
  font-weight: 500;
  color: #4a5568;
  letter-spacing: 0.3px;
}

/* 深色模式时间显示样式 */
html.dark .time-date {
  color: #e2e8f0 !important;
}

html.dark .time-time {
  color: #a0aec0 !important;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-buttons .n-button {
  min-width: 50px;
  height: 28px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-buttons .n-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 🎯 响应式设计 */
@media (max-width: 1200px) {
  .order-info-card {
    max-width: 240px;
  }

  .customer-info-card,
  .price-info-card,
  .time-info-card {
    font-size: 13px;
  }
}

/* 🌙 深色模式适配 */
html.dark .data-table :deep(.n-data-table-th) {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: #ecf0f1;
}

/* 深色模式表格行悬停效果 - 彩虹色动态渐变效果 */
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.3) 0%,
      rgba(255, 165, 0, 0.3) 12.5%,
      rgba(255, 255, 0, 0.3) 25%,
      rgba(0, 255, 0, 0.3) 37.5%,
      rgba(0, 255, 255, 0.3) 50%,
      rgba(0, 0, 255, 0.3) 62.5%,
      rgba(75, 0, 130, 0.3) 75%,
      rgba(238, 130, 238, 0.3) 87.5%,
      rgba(255, 0, 0, 0.3) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.3);
  z-index: 0;
}

html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

/* 深色模式选中行的彩虹色动态渐变效果 */
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.35) 0%,
      rgba(255, 165, 0, 0.35) 12.5%,
      rgba(255, 255, 0, 0.35) 25%,
      rgba(0, 255, 0, 0.35) 37.5%,
      rgba(0, 255, 255, 0.35) 50%,
      rgba(0, 0, 255, 0.35) 62.5%,
      rgba(75, 0, 130, 0.35) 75%,
      rgba(238, 130, 238, 0.35) 87.5%,
      rgba(255, 0, 0, 0.35) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.35);
  z-index: 0;
}

html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

html.dark .order-number {
  background: linear-gradient(135deg, #3498db, #5dade2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

html.dark .customer-avatar {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

/* 深色模式固定列样式 */
html.dark .data-table :deep(.n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-td.n-data-table-td--fixed-right) {
  position: sticky !important;
  z-index: 10 !important;
  background: var(--n-td-color) !important;
}

/* 深色模式固定列在悬浮时的背景处理 */
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 深色模式固定列在选中时的背景处理 */
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 深色模式表格单元格文字样式 */
html.dark .data-table :deep(.n-data-table-td) {
  color: #e8eaed !important;
  font-weight: 500;
}

/* 深色模式表格行悬停样式 */
html.dark .data-table :deep(.n-data-table-tr:hover) {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

/* 数字类型文字样式 */
.data-table :deep(.n-data-table-td) .unit-price,
.data-table :deep(.n-data-table-td) .total-price,
.data-table :deep(.n-data-table-td) .quantity-badge {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

/* 订单号样式 */
.data-table :deep(.n-data-table-td) .order-number {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-weight: 700;
  font-size: 14px;
  letter-spacing: 0.5px;
}

/* 客户信息文字样式 */
.data-table :deep(.n-data-table-td) .customer-name,
.data-table :deep(.n-data-table-td) .product-name {
  font-weight: 600;
  font-size: 15px;
}

/* 状态标签文字样式 */
.data-table :deep(.n-data-table-td) .n-tag {
  font-weight: 600;
  font-size: 13px;
  letter-spacing: 0.2px;
}

/* 紧凑搜索表单样式 */
.compact-search-container {
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 8px 8px;
}

.compact-search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.compact-search-form .n-form-item {
  margin-bottom: 0 !important;
}

.compact-input {
  width: 200px;
}

.compact-select {
  width: 200px;
}

.compact-btn {
  height: 28px;
  border-radius: 6px;
  font-size: 12px;
  padding: 0 12px;
}

/* 现代化弹窗样式 */
.modern-modal {
  backdrop-filter: blur(10px);
}

.modern-modal :deep(.n-card) {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
}

.modal-header {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}

.modal-title-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
}

.modal-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 8px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.modal-title-text h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.modal-subtitle {
  margin: 4px 0 0;
  font-size: 14px;
  color: #666;
  opacity: 0.8;
}

.modal-content {
  padding: 24px;
  max-height: 60vh;
  overflow-y: auto;
}

.form-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-section {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e8e8e8;
}

.section-title {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.form-row {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.form-item {
  flex: 1;
  min-width: 200px;
}

.form-item.full-width {
  width: 100%;
}

.modern-input :deep(.n-input) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  background: white;
}

.modern-input :deep(.n-input:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.modern-input :deep(.n-input:focus-within) {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(64, 169, 255, 0.2);
}

.modern-select :deep(.n-base-selection) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.modern-select :deep(.n-base-selection:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.modern-textarea :deep(.n-input) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.modern-textarea :deep(.n-input:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.total-amount :deep(.n-input-number) {
  background: linear-gradient(135deg, #f6ffed 0%, #f6ffed 100%);
  border: 1px solid #b7eb8f;
}

.total-amount :deep(.n-input-number .n-input) {
  background: transparent;
  font-weight: 600;
  font-size: 16px;
  color: #52c41a;
}

.modal-actions {
  padding: 16px 24px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  justify-content: flex-end;
}

.cancel-btn {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  border-color: #40a9ff;
  color: #40a9ff;
}

.confirm-btn {
  border-radius: 8px;
  background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
}

.confirm-btn:active {
  transform: translateY(0);
}

/* 弹窗动画效果 */
.modern-modal :deep(.n-modal) {
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-20px);
  }

  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 紧凑表格头部样式 */
.compact-table-header {
  margin-bottom: 8px;
  display: flex;
  justify-content: flex-start;
  gap: 8px;
}

.compact-add-btn {
  height: 28px;
  padding: 0 12px;
  font-size: 12px;
  border-radius: 6px;
  margin-top: 10px;
  margin-left: 10px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .compact-search-form {
    flex-direction: column;
    gap: 8px;
  }

  .compact-input,
  .compact-select {
    width: 100%;
  }

  .form-row {
    flex-direction: column;
  }

  .form-item {
    min-width: 100%;
  }

  .modern-modal :deep(.n-card) {
    margin: 16px;
    width: calc(100% - 32px) !important;
  }
}

.pagination-section {
  flex-shrink: 0;
  padding: 8px 20px;
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-top: none;
  border-radius: 0 0 12px 12px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 时间显示样式 */
.time-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.time-date {
  font-size: 13px;
  color: #1890ff;
  font-weight: 500;
}

.time-time {
  font-size: 12px;
  color: #666;
  font-family: Monaco, Consolas, monospace;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: var(--spacing-md);
  }

  .table-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
}
</style>